import React, { useEffect,useState } from 'react'
import { addNum, reduceNum } from "../reducers/numReducer"
import { initList, addListItem, delList } from "../reducers/listReducer"
import { useSelector, useDispatch } from "react-redux"

export default function News() {
  let num = useSelector((state: any) => state.numInfo.num);
  let list = useSelector((state: any) => state.listInfo);
  let dispatch = useDispatch();
  let  [info,setInfo] = useState<any>({})


  useEffect(() => {
    if (!list.length) {
      setTimeout(() => {//模拟数据请求
        dispatch(initList([{ id: 1, username: "leson", userage: 18 }, { id: 2, username: "lulu", userage: 18 }]))
      }, 1000);
    }

  }, [])



  return (
    <div>news {num}
      <button onClick={() => {
        dispatch(addNum(19))
      }}>加法</button>
      <button onClick={() => {
        dispatch(reduceNum(9));
      }}>减法</button>
      <hr />
      <div>
        <div>用户名 <input onChange={(e)=>{
          setInfo({...info,username:e.target.value})

        }}/> </div>
       <div>年龄 <input onChange={(e)=>{
          setInfo({...info,userage:e.target.value})

        }}/> </div>
        <button onClick={()=>{
           dispatch(addListItem({...info,id:666}))
        }}>新增</button>
      </div>
      <div className='tr'>
        <div className='td'>编号</div>
        <div className='td'>姓名</div>
        <div className='td'>年龄</div>
        <div className='td'>操作</div>
      </div>
      {list.map((item:any)=>{
        return  <div className='tr' key={item.id}>
        <div className='td'>{item.id}</div>
        <div className='td'>{item.username}</div>
        <div className='td'>{item.userage}</div>
        <div className='td' onClick={()=>{
          dispatch(delList(item.id));
        }}>删除</div>
      </div> 
      })}


    </div>
  )
}
